package db

import (
	"fmt"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"mall_frontend_api/biz/config"
	"mall_frontend_api/biz/dal"
)

var db *gorm.DB

func MustInit() {
	var err error
	dbConfig := config.Values.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.DBName,
	)
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic(err)
	}

	dal.SetDefault(db)
	hlog.Info("db链接成功")
}

func GetDB() *gorm.DB {
	return db
}
